package com.imooc.searchcountdown;

import com.google.common.util.concurrent.ThreadFactoryBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * search请求线程池
 * 单例
 *
 * @author ChangLiang
 * @date 2019/3/6
 */
public class SearchRequestThreadPool {

    private static final Logger LOGGER = LoggerFactory.getLogger(SearchRequestThreadPool.class);

    private Integer corePoolSize = 4;

    private Integer maximumPoolSize = 4;

    private Integer capacity = 20;

    ThreadFactory threadFactory = new ThreadFactoryBuilder().setNameFormat("search-request-pool-%d").build();

    private ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
            corePoolSize
            , maximumPoolSize
            , 0L
            , TimeUnit.MILLISECONDS
            , new ArrayBlockingQueue<>(capacity)
            , threadFactory
            , ((r, executor) -> LOGGER.info("被拒绝任务为" + r.toString()))
    );

    public ThreadPoolExecutor getThreadPoolExecutor() {
        return threadPoolExecutor;
    }

    private SearchRequestThreadPool() {
    }

    private static class Singleton {

        private static SearchRequestThreadPool instance;

        static {
            instance = new SearchRequestThreadPool();
        }

    }

    public static ThreadPoolExecutor getExecutor() {
        return Singleton.instance.getThreadPoolExecutor();
    }

}
